<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search ref="customSearchRef" v-slot="{ params }"  @submit="handleInitTable">

      <t-col :span="3">
        <t-form-item label="租户名" name="name">
           <t-input v-model:value="params.name" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="联系人" name="contactName">
           <t-input v-model:value="params.contactName" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="联系手机" name="contactMobile">
           <t-input v-model:value="params.contactMobile" clearable placeholder="" />
        </t-form-item>
      </t-col>
      
      <t-col :span="3">
        <t-form-item label="租户状态" name="status">
          <t-select
            v-model:value="params.status"
            :options="dictionaryStore.get('common_status')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="创建时间" name="createTime">
          <t-date-range-picker
            allow-input
            v-model:value="params.createTime"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table
      ref="customTableRef"
      row-key="id"
      :columns="columns"
      :api="tenantListCRUD.page"
      column-controller-key="SystemTenant"
    >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-button
            v-permission="['system:tenant:create']"
            @click="handleOpenDialog('create', { 
              status: 0
              })"
          >
            新建租户
          </t-button>
        </div>
      </template>
   

      <template #status="{ row }">
        <t-tag theme="primary" variant="light">
          {{ dictionaryStore.analysis('common_status', row.status) }}
        </t-tag>
      </template>
      <template #packageId="{ row }">
        <t-tag :theme="row.packageId==0?'danger':'success'" variant="light">
          {{ ([...packageList,{name:'系统租户',id:0}]).find((item) => item.id == row.packageId)?.name }}
        </t-tag>
      </template>
      <template #createTime="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #expireTime="{ row }">
        {{ dayjs(row.expireTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <t-link
            v-permission="['system:tenant:query']"
            theme="primary"
            @click="handleOpenDialog('read', { id: row.id })"
          >
            详情
          </t-link>
          <t-link
            v-permission="['system:tenant:update']"
            theme="primary"
            @click="handleOpenDialog('update', { id: row.id })"
          >
            编辑
          </t-link>
          <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
            <t-link v-permission="['system:tenant:delete']" theme="danger"> 删除 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </custom-table>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly, mode }"
      :api-map="tenantListCRUD"
      header="*租户"
      :on-before-set-data="handleDialogSetData"
      @request-success="handleDialogRequestSuccess"
    >
      <t-form-item label="租户名" name="name" :rules="[{ required: true, message: '请输入租户名' }]">
        <t-input v-model:value="formData.name" placeholder="请输入租户名" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="租户套餐" name="packageId" :rules="[{ required: true, message: '请选择租户套餐' }]">
        <t-select
          v-model:value="formData.packageId"
          :options="packageList"
          :keys="{ label: 'name', value: 'id' }"
          placeholder="请选择租户套餐"
          clearable
          filterable
          :readonly="readonly"
          @clear="formData.packageId = null"
        />
      </t-form-item>
      <t-form-item label="联系人" name="contactName" :rules="[{ required: true, message: '请输入联系人' }]">
        <t-input v-model:value="formData.contactName" placeholder="请输入联系人" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="联系手机" name="contactMobile" >
        <t-input v-model:value="formData.contactMobile" placeholder="请输入联系手机" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item v-if="mode==='create'" label="用户名称" name="username" :rules="[{ required: true, message: '请输入用户名称' }]">
        <t-input v-model:value="formData.username" placeholder="请输入用户名称" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item v-if="mode==='create'" label="用户密码" name="password" :rules="[{ required: true, message: '请输入用户密码' }]">
        <t-input type="password" v-model:value="formData.password" placeholder="请输入用户密码" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item  label="账户额度" name="accountCount" :rules="[{ required: true, message: '请输入账户额度' }]">
        <t-input-number style="width: 100%;" v-model:value="formData.accountCount" placeholder="请输入账户额度" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item
        label="过期时间"
        name="expireTime"
        :rules="[{ required: true, message: '请选择过期时间' }]"
      >
        <t-date-picker 
          allow-input
          v-model:value="formData.expireTime"
          clearable
          placeholder="请选择过期时间"
          value-type="time-stamp"
          :readonly="readonly"
          style="width: 100%"
          @change="
            (value) => {
              if (value) {
                value = dayjs(value).format('YYYY-MM-DD 00:00:00');
                value = dayjs(value).valueOf();
              }
              formData.expireTime = value ? value : undefined;
            }
          "
        />
      </t-form-item>
      <t-form-item  label="绑定域名" name="website" :rules="[{ required: true, message: '请输入绑定域名' }]">
        <t-input v-model:value="formData.website" placeholder="请输入绑定域名" clearable :readonly="readonly" />
      </t-form-item>
  
      <t-form-item label="租户状态" name="status" :rules="[{ required: true, message: '请选择租户状态' }]">
        <t-switch v-model:value="formData.status" :custom-value="[0, 1]" :disabled="readonly" />
      </t-form-item>


    </custom-dialog>
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'SystemTenant',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { onMounted, onUpdated, ref, useTemplateRef } from 'vue';

import { tenantListCRUD } from '@/api/tenant/list';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';

import { useDictionaryStore } from '@/store';
import { getTenantPackage } from '@/api/tenant/package';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'name', title: '租户名', width: 100 },
  { colKey: 'packageId', title: '租户套餐' },
  { colKey: 'contactName', title: '联系人' },
  { colKey: 'contactMobile', title: '联系手机',width:180 },
  { colKey: 'accountCount', title: '账号额度' },
  { colKey: 'expireTime', title: '过期时间', width: 180 },
  { colKey: 'website', title: '绑定域名', width: 180 },
  { colKey: 'status', title: '租户状态' },
  { colKey: 'createTime', title: '创建时间', width: 180 },
  { colKey: 'operation', title: '操作', width: 160, fixed: 'right' },
];
// 处理初始化表格
const handleInitTable = () => {
  const params = { ...customSearchRef.value.params };
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleInitTable();
});
onUpdated(() => {
  handleRefreshTable()
})
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {

};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  tenantListCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 租户套餐
const packageList =  ref([]);
// 处理获取租户套餐列表
const handleGetPackageList = () => {
  getTenantPackage()
    .then((data) => {
      packageList.value = data;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetPackageList();
</script>

<style lang="less" scoped></style>
